<?php

namespace app\common\letterbusiness;

use \think\Session;
use app\common\mysql\LetterUsers as userMysql;
use app\common\letterbusiness\User as UserBn;
use app\common\letterbusiness\upload\Upload as uploadBn;
use app\common\redis\db0\Userinfo as userRedis;
use app\common\letterbusiness\user\Point as pointBn;
use app\common\letterbusiness\user\UserSign as userSignBn;
use app\common\letterbusiness\Coupon as couponBn;
use app\extra\WeixinSDK\Xcx\WXBizDataCrypt;

/**
 * 微信快捷登录
 */
class Quicklogin extends \app\common\letterbusiness\AbstractModel {

    /**
     * 获取微信用户信息保存
     * @param type $mobile
     * @return type
     */
    public static function savequicklogin($wxuserinfo, $show = null) {
        if (empty($wxuserinfo['unionid'])) {
            exception('参数错误', 100004);
        }

        if (!isset($wxuserinfo['headimgurl'])) {
            $wxuserinfo['headimgurl'] = 'http://qhimg.qiu7.net/static/index/img/logo.png';
            $wxuserinfo['localheadimgurl'] = 'http://qhimg.qiu7.net/static/index/img/logo.png';
        }
        if (!empty($wxuserinfo['nickname'])) {
            $wxuserinfo['nickname'] = urldecode($wxuserinfo['nickname']);
        }
        if (!empty($wxuserinfo['province'])) {
            $wxuserinfo['province'] = urldecode($wxuserinfo['province']);
        }

        $memberinfo = userMysql::name('letter_users')->where(array('unionid' => $wxuserinfo['unionid']))->find();

        //微信用户ID是否存在 
        if (!empty($memberinfo['unionid']) && !empty($wxuserinfo['unionid'])) {
            $data = array();
            if ($wxuserinfo['headimgurl']) {
                if (empty($memberinfo['localheadimgurl'])) {
                    $data['headimgurl'] = $wxuserinfo['headimgurl'];
                    $data['nickname'] = $wxuserinfo['nickname'];
                    //生成图片
                    $resourceHost = config('upyun.resourcesHost');
                    $createpath = "/" . date("Y") . "/" . date("m") . "/" . date("d") . "/";
                    $newurl = $resourceHost . $createpath . md5($data['headimgurl']) . ".jpg";
                    $temp['imgurl'] = $data['headimgurl'];
                    $temp['newimgurl'] = $newurl;
                    $temp['imgnewname'] = $createpath . md5($data['headimgurl']) . ".jpg";

                    $img = uploadBn::uploadavurl($temp);
                    if (isset($img['dest_file_name']) && !empty($img['dest_file_name'])) {
                        $data['localheadimgurl'] = $img['dest_file_name'];
                    }
                }
            }
            if ($data) {
                userMysql::name('letter_users')->where(array('unionid' => $wxuserinfo['unionid']))->update($data);
            }
            $userdata = UserBn::userInfo($memberinfo['user_id']);
            $data['sso'] = UserBn::calcSso($memberinfo['user_id']);
            //用户是否开启信息提醒  
            $show = $userdata;
            $show['sso'] = $data['sso'];
            return $show;
        }
        $data['nickname'] = isset($wxuserinfo['nickname']) ? $wxuserinfo['nickname'] : '';
        $data['province'] = isset($wxuserinfo['province']) ? $wxuserinfo['province'] : '';
        $data['headimgurl'] = $data['avatar'] = isset($wxuserinfo['headimgurl']) ? $wxuserinfo['headimgurl'] : '';
        $data['openid'] = isset($wxuserinfo['openid']) ? $wxuserinfo['openid'] : '';
        $data['unionid'] = isset($wxuserinfo['unionid']) ? $wxuserinfo['unionid'] : '';
        $data['reg_time'] = $data['last_login'] = time();
        //生成图片
        if ($data['headimgurl']) {
            //生成图片
            $resourceHost = config('upyun.resourcesHost');
            $createpath = "/" . date("Y") . "/" . date("m") . "/" . date("d") . "/";
            $newurl = $resourceHost . $createpath . md5($data['headimgurl']) . ".jpg";
            $temp['imgurl'] = $data['headimgurl'];
            $temp['newimgurl'] = $newurl;
            $temp['imgnewname'] = $createpath . md5($data['headimgurl']) . ".jpg";

            $img = uploadBn::uploadavurl($temp);
            if (isset($img['dest_file_name']) && !empty($img['dest_file_name'])) {
                $data['localheadimgurl'] = $img['dest_file_name'];
            }
        }

//重新获取会员ID 
        $userdata = UserBn::adduser($data);
        $data = $userdata;
        return $data;
    }

    /**
     * 获取微信用户信息
     * 
     */
    public function getwxinfo($code = null, $access_token = null, $openid = null, $unionid = null) {
        $wxopenid = new \app\extra\WeixinSDK\WxOpenidWap();
//根据相应类型获取信息
        $access_token_info = $this->gettype($code, $access_token, $openid, $unionid);
        if (!isset($access_token_info['errcode'])) {
            return $access_token_info;
        }
        if ($access_token_info['errcode'] != 0) {
            return $access_token_info;
        }
//刷新或续期access_token使用
        $refresh_token_info = $wxopenid->getrefreshtoken($access_token_info['refresh_token']);
        $refresh_token_info = json_decode($refresh_token_info, TRUE);
        if (!isset($refresh_token_info['refresh_token'])) {
            return $refresh_token_info;
        }
//获取微信用户 信息
        $userinfo = $wxopenid->getuserinfo($refresh_token_info['access_token'], $refresh_token_info['openid']);

        $userinfo = json_decode($userinfo, TRUE);

        $userinfo['access_token'] = $refresh_token_info['access_token'];
        $userinfo['refresh_token'] = $refresh_token_info['refresh_token'];
        //保存数据 
        $data = self::savequicklogin($userinfo);

        return $data;
    }

    /**
     * 通过unionid(mysql)\code\openid&access_token获取用户信息
     * @param type $unionid
     * @param type code
     * @param type $userinfo
     * @param type $openid,access_token
     * @return array
     */
    public function gettype($code = '', $access_token = '', $openid = '', $unionid = '') {
//code 获取 $access_token 信息
        $wxopenid = new \app\extra\WeixinSDK\WxOpenidWap();

        if (!empty($code)) {
            $access_token_info = $wxopenid->gettokenbycode($code);
            $access_token_info = json_decode($access_token_info, TRUE);
            if (isset($access_token_info['access_token'])) {
                $access_token_info['errcode'] = 0;
                return $access_token_info;
            }
        } elseif (!empty($access_token) && !empty($openid)) {
//检验授权凭证（access_token）是否有效    		
            return array('errcode' => 0, 'access_token' => $access_token, 'refresh_token' => $access_token, 'openid' => $openid);
        } elseif (!empty($unionid)) {
//从数据库查用户数据
            $userinfo = userMysql::name('letter_users')->where(array('unionid' => $unionid))->find();
            if (empty($userinfo)) {
                return array("errcode" => 40003, "errmsg" => "invalid openid or code or unionid");
            }

            return $userinfo;
        }

        return array("errcode" => 40003, "errmsg" => "invalid openid or code or unionid");
    }

    /**
     * 手机绑定验证
     * $type weixin,qq,sina
     */
    public static function mobilecode($mobile, $user_id) {
        $userinfo = userMysql::name('letter_users')->where(array("mobile" => $mobile))->field('user_id,unionid')->find();
        //如果手机号
        if (!empty($userinfo['unionid'])) {
            //手机用户是否有绑定type           
            exception('当前用户被绑定', 110033);
            return $userinfo['user_id'];
        }
        return $userinfo['user_id'];
    }

    /*
     * 手机号码用户与第三方绑定
     * @param type $mobile
     * @param type $code
     * @param type $user_id　
     *  @param type $type weixin ,qq,sina
     * @return boolean
     */

    public static function quickloginbind($post) {
        $data['mobile'] = $mobile = $post['mobile'];
        $data['user_code'] = $code = $post['code'];
        $user_id = $post['user_id'];
        // $type = $post['type'];
        //验证码是不是有效
        if (!User::verfiytest($data, 2)) {
            exception('验证码错误', 110021);
        }
        //验证手机是否被绑定
        //获取加密后的手机号 
        $mobile_user_id = self::mobilecode($mobile, $user_id); //手机有存在的用户ID
        $userinfo = userMysql::name('letter_users')->field('mobile,user_lasttime,unionid,openid')->where(array("user_id" => $user_id))->find();
        $user_phone = $userinfo['mobile'];
        if (!empty($user_phone)) {
            exception('当前用户已绑定手机号', 110033);
        }
        userMysql::startTrans();
        //手机已存在更新快捷登录的用户ID  
        if ($mobile_user_id > 1) {
            $r2 = UserBn::userMerge(array('from_user_id' => $user_id, 'to_user_id' => $mobile_user_id));
            if ($r2 != true) {
                exception('绑定失败', 110034);
            }
            $user_id = $mobile_user_id;
        } else {
            //更新手机号
            //获取加密后的手机号
            $encodmobile = $data['mobile']; // self::encrypt_phone($data['user_phone']);
            $updatewhere = array('mobile' => $encodmobile);
            $data = userMysql::name('letter_users')->where(array("user_id" => $user_id))->update($updatewhere);
            if ($data != true) {
                exception('绑定失败', 110034);
            }
        }
        $redis = new userRedis();
        $userkey = "userinfo:" . $user_id;
        $redis->del($userkey);

        //赠品金豆
        $updatemoney['user_id'] = $user_id;
        $updatemoney['money_type'] = 27;
        $updatemoney['money'] = 25;
        $updatemoney['memo'] = "绑定获得";
        $r2 = UserBn::updateMoney($updatemoney);
        if ($r2 != true) {
            userMysql::rollback();
            exception('注册失败', 110038);
        }
        //赠品嗨豆
        $pointdata = pointBn::updatePointBySource(array('user_id' => $user_id, 'source_type' => 11));
        //赠送券 
        $coupon['coupon_endtime'] = date("Y-m-d", strtotime("+7 day"));
        $coupon['coupon_id'] = 2;
        $coupon['user_id'] = $user_id;
        $r3 = couponBn::send($coupon);
        if ($r3 != true) {
            userMysql::rollback();
            exception('注册失败', 110038);
        }
        userMysql::commit();
        $user = UserBn::userInfo($user_id);
        $user['sso'] = User::calcSso($user['user_id']);
        $user['total_point'] = $pointdata['total_point'];
        $user['point'] = $pointdata['point'];
        $user['sign_money'] = $updatemoney['money'];
        $user['coupon_name'] = "8折";

        $user['sso'] = User::calcSso($user['user_id']);
        //是否已签到 
        $user['is_sign'] = userSignBn::isSign($user_id);
        //当前用户积分 
        $user['total_point'] = $pointdata['total_point'];
        $user['point'] = $pointdata['point'];
        $user['is_register'] = 2;
        return $user;
    }

    /**
     * 绑定快捷登录 
     */
    public static function binduser($post) {
        $user = UserBn::userInfo($post['user_id']);
        if (empty($user['mobile'])) {
            exception('当前用户不能绑定', 110038);
        }
        if (!empty($user['unionid'])) {
            exception('当前用户已被绑定', 110038);
        }
        $wxinfo = UserBn::getUserInfo(array('unionid' => $post['unionid']), 'mobile,user_id');
        userMysql::startTrans();
        try {
            if (isset($wxinfo['mobile']) && !empty($wxinfo['mobile'])) {
                exception('当前微信已被绑定', 110038);
            }

            $user_id = $post['user_id'];
            //进行账号合并
            if (isset($wxinfo['user_id']) && !empty($wxinfo['user_id'])) {
                $mergedata['from_user_id'] = $wxinfo['user_id'];
                $mergedata['to_user_id'] = $post['user_id'];
                UserBn::userMerge($mergedata);
                userMysql::commit();
                $user = UserBn::userInfo($post['user_id']);
                $user['sso'] = UserBn::calcSso($user['user_id']);
                $user['total_point'] = $user['point'];
                $user['point'] = 0;
                $user['sign_money'] = 0;
                $user['coupon_name'] = "";
                $user['sso'] = UserBn::calcSso($user['user_id']);
                $user['is_register'] = 2;

                return $user;
            } else {
                $r = UserBn::updateUserinfo($post['user_id'], array('unionid' => $post['unionid'], 'openid' => $post['openid']));

                //赠品金豆
                $updatemoney['user_id'] = $post['user_id'];
                $updatemoney['money_type'] = 27;
                $updatemoney['money'] = 25;
                $updatemoney['memo'] = "绑定获得";
                $r2 = UserBn::updateMoney($updatemoney);
                if ($r2 != true) {
                    userMysql::rollback();
                    exception('注册失败', 110038);
                }
                //赠品嗨豆
                $pointdata = pointBn::updatePointBySource(array('user_id' => $user_id, 'source_type' => 11));
                //赠送券 
                $coupon['coupon_endtime'] = date("Y-m-d", strtotime("+7 day"));
                $coupon['coupon_id'] = 2;
                $coupon['user_id'] = $user_id;
                $r3 = couponBn::send($coupon);
                if ($r3 != true) {
                    userMysql::rollback();
                    exception('注册失败', 110038);
                }
                userMysql::commit();
                $user = UserBn::userInfo($user_id);
                $user['sso'] = UserBn::calcSso($user['user_id']);
                $user['total_point'] = $pointdata['total_point'];
                $user['point'] = $pointdata['point'];
                $user['sign_money'] = $updatemoney['money'];
                $user['coupon_name'] = "8折";

                $user['sso'] = UserBn::calcSso($user['user_id']);

                //当前用户积分 
                $user['total_point'] = $pointdata['total_point'];
                $user['point'] = $pointdata['point'];
                $user['is_register'] = 2;
                return $user;
            }
            return true;
        } catch (\Exception $e) {
            userMysql::rollback();
            exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 微信小程序获取解密
     */
    public static function checkWxXCX($post) {
//        $appid = 'wx6df8e0040d1d0a2d';
//        $secretkey = '02b230aca239f6ebf7cd0d4e105f763a';
        $appid = 'wx9f3e8b720a879bc1';
        $secretkey = '6a7cf26d54a40410e0221397980d0ecb';
        $datacode2 = file_get_contents('https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $secretkey . '&js_code=' . $post['code'] . '&grant_type=authorization_code');
        $data3 = json_decode($post['rawData'], true);
        $datacode = json_decode($datacode2, true);
        if (isset($datacode['session_key'])) {
            $pc = new \app\extra\WeixinSDK\Xcx\WXBizDataCrypt($appid, $datacode['session_key']);
            $data2 = $pc->decryptData($post['encryptedData'], $post['iv'], $data3);
            $data2 = json_decode($data2, true);

            $data['unionid'] = $data2['unionId'];
            $data['openid'] = $data2['openId'];
            $data['headimgurl'] = $data3['avatarUrl'];
            $data['sex'] = $data3['gender'];
            $data['nickname'] = $data3['nickName'];
        } else {
            exception($datacode2 . '授权失败' . var_export($datacode, true), 110038);
        }
        return $data;
    }

}
